package cfs.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.dao.DAOException;

import cfs.databean.CFSTransaction;
import cfs.databean.Fund;
import cfs.databean.FundPriceHistory;
import cfs.formbean.TransactionForm;
import cfs.model.FundDAO;
import cfs.model.FundPriceHistoryDAO;
import cfs.model.Model;
import cfs.model.TransactionDAO;

public class ViewTransactionAction extends Action {

	private TransactionDAO transDAO;
	private FundDAO fundDAO;
	private FundPriceHistoryDAO fundPriceDAO;

	public ViewTransactionAction(Model model) {
		transDAO = model.getTransactionDao();
		fundDAO = model.getFundDao();
		fundPriceDAO = model.getFundHistoryDao();
	}

	@Override
	public String getName() {
		return "viewTransaction.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		try {
			List<CFSTransaction> transList = transDAO.getAllTransactions();
			Collections.reverse(transList);
                        ArrayList<String> errors = new ArrayList<String>();
			List<TransactionForm> formList = new ArrayList<TransactionForm>();
			for (CFSTransaction tran : transList) {
				if (tran.getFund_id() > 0) {//sell or buy
					Fund fund = fundDAO.lookup(tran.getFund_id());
					FundPriceHistory fundPrice;
					TransactionForm form;
					if (tran.getExecute_date() != null) {
						fundPrice = fundPriceDAO.lookup(fund.getFund_id(),
								tran.getExecute_date());
						 form = new TransactionForm(tran, fund,
									fundPrice.getPrice());
						 
							
					}else{
						
						 form = new TransactionForm(tran, fund);
					}
					
					formList.add(form);
				} else {//deposit or check
					
					
					
					TransactionForm form = new TransactionForm(tran);
					formList.add(form);
				}
			}
                        if(formList.size()<=0){
                            errors.add("There is currently no transactions");
                            request.setAttribute("errors", errors);
                        }
			request.setAttribute("formList", formList);
			return "viewTransactionHistory.jsp";
		} catch (DAOException e) {
			return "error.jsp";
		}
	}

}
